//
//  XFYScrollView.m
//  SDKSample
//
//  Created by 小肥羊 on 15/7/10.
//  Copyright (c) 2015年 Zhu‘s Game House. All rights reserved.
//

#import "XFYScrollView.h"

@implementation XFYScrollView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

#pragma mark - 初始化
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.scrollView.delegate = self;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.contentMode = UIViewContentModeCenter;
        self.scrollView.pagingEnabled = YES;        //影响点击滚动出发
        self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height - 30, frame.size.width, 30)];
        self.pageControl.currentPage = 0;
        self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        self.firstView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.firstView.showsVerticalScrollIndicator = NO;
        self.firstView.showsHorizontalScrollIndicator = NO;
        self.firstView.contentMode = UIViewContentModeCenter;
        self.firstView.pagingEnabled = YES;        //影响点击滚动出发
        self.firstView.contentSize = CGSizeMake(self.bounds.size.width * 2, self.bounds.size.height);
        [self.firstView setHidden:YES];
        
        [self addSubview:self.scrollView];
        [self addSubview:self.firstView];
        [self addSubview:self.pageControl];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame animationDuration:(NSTimeInterval)animationDuration
{
    self = [self initWithFrame:frame];
    if (animationDuration > 0.0) {
        self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(self.animationDuration = animationDuration)
                                                               target:self
                                                             selector:@selector(animationTimerDidFired:)
                                                             userInfo:nil
                                                              repeats:YES];
        [self.animationTimer pauseTimer];
    }
    return self;
}

#pragma mark - Set
- (void)setContentViews:(NSMutableArray *)contentViews
{
    if (_contentViews) {
        for (UIView *contentView in _contentViews) {
            [contentView removeFromSuperview];
        }
        for(UIView *contentView in [self.firstView subviews])
        {
            [contentView removeFromSuperview];
        }
    }
    self.currentPage = 0;
    _contentViews = contentViews;
    self.scrollView.contentSize = CGSizeMake(_contentViews.count * CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
    self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.scrollView.frame), 0);
    for (NSInteger i=0; i<_contentViews.count; i++) {
        UIView *contentView = [contentViews objectAtIndex:i];
        [contentView setFrame:(CGRect){CGPointMake(self.scrollView.frame.size.width * i, 0), self.scrollView.frame.size}];
        contentView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentViewTapAction:)];
        [contentView addGestureRecognizer:tapGesture];
        [self.scrollView addSubview:contentView];
        if (i==0) {
            UIView *firstContentView = [self duplicate:contentView];
            firstContentView.frame = (CGRect){CGPointMake(self.firstView.frame.size.width, 0), self.firstView.frame.size};
            [self.firstView addSubview:firstContentView];
        } else if (i==_contentViews.count-1) {
            UIView *lastContentView = [self duplicate:contentView];
            lastContentView.frame = (CGRect){CGPointZero, self.firstView.frame.size};
            [self.firstView addSubview:lastContentView];
        }
    }
    [self.scrollView setContentOffset:CGPointMake(0, 0)];
    [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
    self.pageControl.numberOfPages = contentViews.count;
}

#pragma mark - 响应事件
- (void)animationTimerDidFired:(NSTimer *)timer
{
    if (self.contentViews.count > 1) {
        self.currentPage ++;
        if (self.currentPage == self.contentViews.count) {
            self.currentPage = 0;
            [self.firstView setHidden:NO];
            [self.firstView setContentOffset:CGPointMake(self.firstView.frame.size.width, 0) animated:YES];
            double delay1 = 0.5;    //设置延时时间
            dispatch_time_t popTime=dispatch_time(DISPATCH_TIME_NOW, delay1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^{
                [self.firstView setHidden:YES];
                [self.firstView setContentOffset:CGPointMake(0, 0) animated:YES];
            });
        }
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * self.currentPage, 0) animated:YES];
        self.pageControl.currentPage = self.currentPage;
    }
}

- (void)contentViewTapAction:(UITapGestureRecognizer *)tap
{
    if (self.clickScrollViewDelegate) {
        [self.clickScrollViewDelegate clickScrollView:self PageIndex:self.currentPage];
    }
}


#pragma mark scrollView delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.animationTimer pauseTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.scrollView]) {
        self.currentPage = scrollView.contentOffset.x/scrollView.frame.size.width;
        [scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * self.currentPage, 0) animated:YES];
        self.pageControl.currentPage = self.currentPage;
    } else if ([scrollView isEqual:self.firstView]) {
        //判断
//        self.currentPage = scrollView.contentOffset.x/scrollView.frame.size.width;
//        [scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * self.currentPage, 0) animated:YES];
//        self.pageControl.currentPage = self.currentPage;
    }
}

//完全复制
- (UIView*)duplicate:(UIView*)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}

@end
